package cn.darkhorse.meswechat.service.impl;

import cn.darkhorse.meswechat.common.WxChatCommon;
import cn.darkhorse.meswechat.service.IWeChatCallBackService;
import cn.darkhorse.meswechat.service.IWeChatUserService;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @description:
 * @author: mr.wang
 * @time: 2023/4/14 14:08
 */
@Service
public class WeChatCallBackServiceImpl implements IWeChatCallBackService{
	
	@Resource
	private IWeChatUserService weChatUserService;
	
	@Override
	public String urlAttestation(HttpServletRequest request) {
		String echostr = null;
		String method = request.getMethod();
		if("GET".equals(method)){
			String signature = request.getParameter("signature");
			String timestamp = request.getParameter("timestamp");
			String nonce = request.getParameter("nonce");
			String[] str = {WxChatCommon.WX_TOKEN,timestamp,nonce};
			Arrays.sort(str); //字典排序
			String bigStr = str[0] + str[1] + str[2];
			String digest = sha1(bigStr);//sha1加密
			//请求是否来自微信
			if(digest.equals(signature)){
				 echostr = request.getParameter("echostr");
			}
		}
		return echostr;
	}
	
	@Override
	public void unbindBindingData(String params) {
		//解析xml
		Map<String, Object> map = readStringXmlOut(params);
		String msgType = String.valueOf(map.get("MsgType"));
		if(WxChatCommon.WX_EVENT.equals(msgType)){
			//事件类型
			String event = String.valueOf(map.get("Event"));
			if(WxChatCommon.WX_SUBSCRIBE.equals(event)){
				weChatUserService.wxBindUsers(map);
			}else if (WxChatCommon.WX_UNSUBSCRIBE.equals(event)){
				weChatUserService.wxUnbindUser(map);
			}else if(WxChatCommon.WX_SCAN.equals(event)){
				weChatUserService.wxUpdateBindUser(map);
			}else {
			
			}
		
		}
		
	}
	
	//加解密
	private String sha1 (String data){
		char[] chs = new char[1];
		try {
			MessageDigest md = MessageDigest.getInstance("SHA1");
			byte[] b = data.getBytes(); //字符转字节数组
			md.update(b); //使用指定字节更新摘要
			byte[] d = md.digest(); //获取密文
			int len = d.length;
			String str = "0123456789abcdef"; //16进制字符串
			char[] ch = str.toCharArray();
			chs = new char[len * 2]; //创建2倍字节数组
			for(int i = 0,k=0;i<len;i++){
				byte b2 = d[i]; //获取摘要计算后的数组字节
				chs[k++] = ch[b2 >>> 4 & 0xf]; // >>>：无符号右移 &：按位与  0xf: 0-15的数字
				chs[k++] = ch[b2 & 0xf];
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return new String(chs);
	}
	
	
	
	
	/**
	 * 将xml字符串转换成map
	 * @param xml xml数据
	 * @return Map
	 */
	public static Map<String,Object> readStringXmlOut(String xml) {
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			Document doc = DocumentHelper.parseText(xml);
			Element root = doc.getRootElement();
			Iterator it = root.elementIterator();
			while (it.hasNext()) {
				Element element = (Element) it.next();
				map.put(element.getName(), element.getTextTrim());
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		
		return map;
	}
}
